<template>
  <view class="add-group">
    <view class="section-box">
      <view class="section-title">
        <view class="title">分组信息</view>
      </view>
      <view class="form-box">
        <view class="form-item">
          <view class="item-label">分组名称</view>
          <view class="item-content">
            {{ groupName }}
          </view>
        </view>
        <view class="form-item">
          <view class="item-label">分组编号</view>
          <view class="item-content">
            {{ groupNumber }}
          </view>
        </view>
        <view class="form-item">
          <view class="item-label">应用场景</view>
          <view class="item-content">
            {{ sceneName }}
          </view>
        </view>
        <view class="form-item">
          <view class="item-label">所在区域</view>
          <view class="item-content">
            {{ areaName }}
          </view>
        </view>
      </view>
    </view>
    <view class="section-box">
      <view class="section-title">
        <view class="title">组内灯具</view>
      </view>
      <view class="lamp-list">
        <view v-for="item in lampList" :key="item" class="lamp-item" :class="{active: activeLamp === item}">
          <view v-if="enableEdit" class="close iconfont icon-close-fill" @click="removeLamp(item)" />
          <image class="lamp-icon" src="@/static/image/icon-lamp.png"></image>
          <view class="lamp-content">
            <view class="line lamp-name">{{ item }}</view>
          </view>
        </view>
      </view>
    </view>
    <uni-popup ref="popup" type="center">
      <view class="add-lamp">
        <view class="title">确定要添加该灯具么？</view>
        <image class="lamp-icon" src="@/static/image/icon-lamp.png"></image>
        <view class="lamp-name">{{ activeLamp }}</view>
        <view class="btn-box">
          <view class="btn" @click="closeAddPop">否</view>
          <view class="btn confirm" @click="addLamp">是</view>
        </view>
      </view>
    </uni-popup>
    <uni-popup ref="removeDialog" type="dialog">
      <uni-popup-dialog type="error" cancelText="否" confirmText="是" content="确定要移除该灯具？" @confirm="doRemove()"></uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import mixin from '@/mixins/index.js'
export default {
  mixins: [mixin],
  data() {
    return {
      isPageShow: false,
      groupName: '',
      groupNumber: '',
      areaName: '',
      sceneName: '',
      areaCode: '',
      areaList: [],
      areaMap: [],
      sceneCode: '',
      sceneList: [],
      sceneMap: [],
      lampList: [],
      activeLamp: '',
      targetRemoveLamp: '',
      requestTask: null,
      enableEdit: false,
      errorCount: 0,
      maxErrorCount: 10
    }
  },
  mounted() {
    this.enableEdit = this.params.canEdit === 'true'
    this.getGroupInfo()
  },
  onShow() {
    this.isPageShow = true
  },
  onHide() {
    this.isPageShow = false
    this.abortLongRequest()
  },
  onUnload() {
    this.isPageShow = false
    this.abortLongRequest()
  },
  methods: {
    getGroupInfo(refresh) {
      const self = this
      uni.request({
        url: '/project_group/get',
        data: {
          id: self.params.groupId
        },
        success(result) {
          if (result.data.success && result.data.data) {
            self.groupName = result.data.data.name || ''
            self.groupNumber = result.data.data.gnum || ''
            self.areaCode = result.data.data.area_id || ''
            self.sceneCode = result.data.data.scene || ''
            try {
              const nodes = JSON.parse(result.data.data.nodes)
              if (Array.isArray(nodes)) {
                self.lampList = nodes
              }
            } catch (e) {
              console.log(e)
            }
            if (!refresh) {
              self.getProjectArea()
              self.getProjectScenario()
              if (self.enableEdit) {
                self.getSelectLamps()
              }
            }
          }
        }
      })
    },
    getProjectArea() {
      const self = this
      uni.request({
        url: '/project_area/list',
        data: {
          xm_id: self.params.projectId
        },
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            const arr = []
            result.data.data.forEach(item => {
              const areaItem = {
                key: item.id,
                value: item.id,
                text: item.name || ''
              }
              self.areaMap[item.id] = areaItem
              arr.push(areaItem)
            })
            self.areaList = arr
            self.areaName = self.areaMap[self.areaCode]?.text || self.areaCode
          }
        }
      })
    },
    getProjectScenario() {
      const self = this
      uni.request({
        url: '/project_scene/list',
        data: {
          xm_id: self.params.projectId
        },
        success(result) {
          if (result.data.success && Array.isArray(result.data.data)) {
            const arr = []
            result.data.data.forEach(item => {
              const sceneItem = {
                key: item.id,
                value: item.id,
                text: item.name || '',
              }
              self.sceneMap[item.id] = sceneItem
              arr.push(sceneItem)
            })
            self.sceneList = arr
            self.sceneName = self.sceneMap[self.sceneCode]?.text || self.sceneCode
          }
        }
      })
    },
    getSelectLamps() {
      const self = this
      self.abortLongRequest()

      if (!self.isPageShow) return
      self.requestTask = uni.request({
        url: '/gw/cmd2',
        data: {
          cmd: 'get_sel_node',
          uid: self.params.gatewayId
        },
        noLoading: true,
        success(result) {
          self.errorCount = 0
          if (result.data?.success && result.data.data) {
            const lampId = result.data.data.uid
            self.activeLamp = lampId
            if (!self.lampList.includes(lampId)) {
              self.$refs.popup.open()
            }
          }
        },
        fail() {
          self.errorCount += 1
        },
        complete(result) {
          if (result.statusCode !== 200) {
            self.errorCount += 1
          }
          if (self.errorCount >= self.maxErrorCount) {
            uni.showToast({
              icon: 'error',
              title: '获取灯具失败'
            })
            return
          }
          setTimeout(self.getSelectLamps, 100)
        }
      })
    },
    abortLongRequest() {
      const self = this
      if (self.requestTask && self.requestTask.abort) {
        self.requestTask.abort()
      }
    },
    closeAddPop() {
      this.$refs.popup.close()
    },
    addLamp() {
      const self = this
      uni.request({
        url: '/project_group/add_node',
        data: {
          id: self.params.groupId,
          uid: self.activeLamp
        },
        success(result) {
          if (result.data.success) {
            uni.showToast({
              icon: 'success',
              title: '添加成功'
            })
            self.$refs.popup.close()
            self.getGroupInfo(true)
          }
        }
      })
    },
    removeLamp(target) {
      this.targetRemoveLamp = target
      this.$refs.removeDialog.open()
    },
    doRemove() {
      const self = this
      uni.request({
        url: '/project_group/del_node',
        data: {
          id: self.params.groupId,
          uid: self.targetRemoveLamp
        },
        success(result) {
          if (result.data.success) {
            uni.showToast({
              icon: 'success',
              title: '移除成功'
            })
            self.getGroupInfo(true)
          }
        }
      })
    },
    goBack() {
      uni.navigateBack();
    }
  }
}
</script>

<style scoped lang="scss">
.add-group {
  padding: 30rpx 30rpx 130rpx;
}
.section-box {
  background-color: $white;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}
.section-title {
  @include section-title;
}
.form-box {
  margin-top: 20rpx;
  .form-item {
    height: 70rpx;
    padding: 10rpx 30rpx 10rpx 150rpx;
    position: relative;
    display: flex;
    align-items: center;
    &:first-child {
      border-top: 0;
    }
    .item-label {
      position: absolute;
      left: 0;
      font-size: $font-size-3;
    }
    .item-content {
      position: relative;
      text-align: right;
      width: 100%;
      font-size: $font-size-2;
      display: flex;
      justify-content: flex-end;
      &.placeholder {
        color: $text-placeholder;
      }
    }
    .select-item {
      width: 350rpx;
    }
  }
}
.lamp-list {
  padding: 30rpx 0;
  display: grid;
  grid-template-columns: repeat(3, 190rpx);
  grid-gap: 30rpx;
}
.lamp-item {
  position: relative;
  padding: 15rpx 16rpx 12rpx 60rpx;
  height: 80rpx;
  font-size: 20rpx;
  border: 2rpx solid $border-base;
  border-radius: 10rpx;
  &.active {
    background-color: rgba($warning, .1);
  }
  .close {
    position: absolute;
    top: -20rpx;
    right: -20rpx;
    color: $danger;
    font-size: 40rpx;
  }
  .lamp-icon {
    position: absolute;
    left: 14rpx;
    top: 18rpx;
    width: 31rpx;
    height: 47rpx;
  }
  .lamp-content {
    display: flex;
    height: 100%;
    align-items: center;
  }
  .lamp-name {
    color: $text-base;
  }
}
.add-lamp {
  border-radius: 10rpx;
  background-color: $white;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 480rpx;
  margin-bottom: 100rpx;
  .title {
    font-size: $font-size-4;
    margin-bottom: 20rpx;
    padding: 40rpx 20rpx 0;
  }
  .lamp-icon {
    width: 72rpx;
    height: 113rpx;
  }
  .lamp-name {
    margin-top: 20rpx;
    color: $text-base;
    font-size: $font-size-6;
  }
  .btn-box {
    margin-top: 30rpx;
    border-top: 2rpx solid $border-base;
    width: 100%;
    display: flex;
    align-items: center;
    .btn {
      font-size: $font-size-4;
      flex: 1;
      padding: 20rpx 10rpx;
      text-align: center;
      &.confirm {
        border-left: 2rpx solid $border-base;
        color: $primary;
      }
    }
  }
}
</style>
